<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="部门" prop="deptId">
   <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id" 
              placeholder="请选择部门"
              filterable 
              :disabled="formData.isDisabled"
            />
      </el-form-item>      
        </el-col>

        <el-col :span="8">
          <el-form-item label="订单日期" prop="orderDate">
        <el-date-picker
          v-model="formData.orderDate"
          type="date"
          value-format="x"
          placeholder="选择订单日期"
          style="width: 100%;"
          :disabled="formData.isDisabled"
        />
      </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" :disabled="formData.isDisabled"/>
      </el-form-item>
        </el-col>
    </el-row>
 
    <el-row :gutter="20">

      <el-col :span="8">
        <el-form-item label="流水号" prop="serialNumber">
        <el-input v-model="formData.serialNumber" placeholder="自动生成" :disabled="true"/>
      </el-form-item>
      </el-col>
      <el-col :span="8"/>
      <el-col :span="8"/>

    </el-row>
    
    
    </el-form>  
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="生产任务单子" name="productionOrders">
        <ProductionOrdersForm ref="productionOrdersFormRef" :pid="formData.id" :isDisabled="formData.isDisabled"/>
      </el-tab-pane>
    </el-tabs>
    <div class="footer">
      <el-button @click="submitForm" type="primary" :disabled="formData.isDisabled" :isDisabled="formData.isDisabled" >确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ProductionOrderApi, ProductionOrderVO } from '@/api/wms/productionorder'
import ProductionOrdersForm from './components/ProductionOrdersForm.vue';
import { defaultProps, handleTree } from '@/utils/tree';
import { getSimpleDeptList } from '@/api/system/dept';
import { useRoute, useRouter } from 'vue-router';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useTagsViewStore } from '@/store/modules/tagsView'
import { PomainApi, PomainVO } from '@/api/wms/pomain'

/** 生产任务单主表 表单 */
defineOptions({ name: 'productionOrderFormCreate' })

const { t } = useI18n() // 国际化
const { push, currentRoute } = useRouter() 
const route = useRoute();
const router = useRouter();
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  serialNumber: undefined,
  deptId: undefined,
  orderDate: new Date().getTime(),
  remark: undefined,
  auditor: undefined,
  auditTime: undefined,
  isDisabled:false

})
const formRules = reactive({
  orderDate: [{ required: true, message: '订单日期不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const { delView } = useTagsViewStore() // 视图操作

/** 子表的表单 */
const subTabsName = ref('productionOrders')
const productionOrdersFormRef = ref()

const deptList = ref<Tree[]>([]) // 树形结构


onMounted(async () => {
  // 加载用户数据
  console.log(route.query.id)
  deptList.value = handleTree(await getSimpleDeptList())

  initFormData(route.query.id ? String(route.query.id) : undefined);
});

/** 初始化表单数据 */
const initFormData = async (id?: any) => {
  if (id) {  
    formLoading.value = true;
    try {
      if(id!='undefined'){
        formData.value = await ProductionOrderApi.getProductionOrder(id);
      }
    
      if(route.query.type=='select')
      {
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }else if(route.query.type=='update'){
        formData.value.isDisabled = false; // 修改时可以编辑
      formType.value = 'update';
      }else if(route.query.type=='create'){
      // formData.value.isDisabled = false; // 新增时可以编辑
      formType.value = 'create';
      resetForm();
      }else{
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }
    } finally {
      formLoading.value = false;
    }
  } else {
    // formData.value.isDisabled = false; // 创建时可以编辑
    resetForm();
    formType.value = 'create';
  }
};

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 校验子表单
  try {
    await productionOrdersFormRef.value.validate();
  } catch (e) {
    subTabsName.value = 'pomains';
    return;
  }
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as PomainVO;
    // 拼接子表的数据
    data.productionOrderss = productionOrdersFormRef.value.getData();
    if (formType.value === 'create') {
      await ProductionOrderApi.createProductionOrder(data);
      ElMessage.success(t('common.createSuccess'));
    } else {
      await ProductionOrderApi.updateProductionOrder(data);
      ElMessage.success(t('common.updateSuccess'));
    }
    delView(unref(currentRoute))
    push('/product/production-order');
  } finally {
    formLoading.value = false;
  }
};
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    serialNumber: undefined,
    deptId: undefined,
    orderDate: new Date().getTime(),
    remark: undefined,
    auditor: undefined,
    auditTime: undefined,
  }
  formRef.value?.resetFields()
}

/** 返回上一页 */
const goBack = () => {
  delView(unref(currentRoute))
    push('/product/production-order');
};
</script>

<style scoped>
.footer {
  margin-top: 20px;
  text-align: right;
}
</style>